﻿using RndMaterialDisposalService.Attrbutes;
using Microsoft.Extensions.Options;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace RndMaterialDisposalService.LoggingProvider
{
    /// <summary>
    /// 日志文件定期清理
    /// </summary>
    [NAutowired(Lifecycle.Singleton,typeof(IHostedService))]
    public class LogClearTask : BackgroundService
    {

        private readonly int saveDays;

        private readonly ILogger<LogClearTask> logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="config"></param>
        /// <param name="_logger"></param>
        public LogClearTask(IOptionsMonitor<LoggerSetting> config, ILogger<LogClearTask> _logger)
        {
            this.saveDays = config.CurrentValue.SaveDays;
            this.logger = _logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {

                    string basePath = Directory.GetCurrentDirectory().Replace("\\", "/") + "/Logs/";

                    if (Directory.Exists(basePath))
                    {
                        List<string> logPaths = Helper.IOHelper.GetFolderAllFiles(basePath).ToList();

                        var deleteTime = DateTime.UtcNow.AddDays(-1 * saveDays);

                        if (logPaths.Count != 0)
                        {
                            foreach (var logPath in logPaths)
                            {
                                var fileInfo = new FileInfo(logPath);

                                if (fileInfo.CreationTimeUtc < deleteTime)
                                {
                                    File.Delete(logPath);
                                }
                            }
                            logger.LogTrace($"已清理{logPaths.Count}个日志文件");
                        }
                    }
                }
                catch(Exception ex)
                {
                    logger.LogError(ex, $"日志文件定期清理任务执行异常:{ex.Message}");
                }

                await Task.Delay(1000 * 60 * 60 * 24, stoppingToken);
            }
        }

    }

    /// <summary>
    /// 
    /// </summary>
    public class LoggerSetting
    {
        /// <summary>
        /// 保存天数
        /// </summary>
        public int SaveDays { get; set; } = 30;
    }
}
